#ifndef RENDERTHREAD_H
#define RENDERTHREAD_H

#include <QObject>
#include <QThread>
#include "ffinclude.h"

class VideoPlayer;

/*
     音视频渲染线程
*/
class RenderThread : public QThread
{
    Q_OBJECT
public:
    explicit RenderThread(VideoPlayer* player);
    ~RenderThread();

    static bool sdlInit();

    void play();
    void pause();
    void stop();
    void step();

signals:
    void inited();
    void eos();
    void timeout();
    void error(const QString& err);

protected:
    void run();

private:
    bool openAudioDevice();
    void closeAudioDevice();
    bool createWindow();
    void destoryWindow(); 
    void renderNextFrame(double *delayTime);    
    void sdlRenderVideoAndText();

    static void sdlAudioDeviceCallback(void *opaque, Uint8 *stream, int len);
    static int synchronize_audio(PlayerInfo *is, int nb_samples);
    static void update_sample_display(PlayerInfo *is, short *samples, int samples_size);
    static int audio_decode_frame(PlayerInfo *is);


    double vp_duration(PlayerInfo *is, Frame *vp, Frame *nextvp);
    double compute_target_delay(double delay, PlayerInfo *is);
    void update_video_pts(PlayerInfo *is, double pts, int64_t pos, int serial);
    inline int compute_mod(int a, int b);
    int realloc_texture(SDL_Texture **texture, Uint32 new_format, int new_width, int new_height, SDL_BlendMode blendmode, int init_texture);
    void get_sdl_pix_fmt_and_blendmode(int format, Uint32 *sdl_pix_fmt, SDL_BlendMode *sdl_blendmode);
    int upload_texture(SDL_Texture **tex, AVFrame *frame, SwsContext **img_convert_ctx) ;
    void calculate_display_rect(SDL_Rect *rect, int scr_xleft, int scr_ytop, int scr_width, int scr_height, int pic_width, int pic_height, AVRational pic_sar);
    void fill_rectangle(int x, int y, int w, int h);
    void stream_toggle_pause(PlayerInfo *is);

     int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params);
    int video_open(PlayerInfo *is);
    void video_audio_display(PlayerInfo *s);
    void video_image_display(PlayerInfo *is);
    
private:
    VideoPlayer* m_player;
    
    bool m_reqStop;
    bool m_reqPause;
    QString m_lastErrorMsg;
    
    SDL_Renderer* m_renderer;
    SDL_Window* m_window;
    SDL_AudioDeviceID m_audioDevice;

    friend void sdlAudioDeviceCallback(void *opaque, Uint8 *stream, int len);
    friend class VideoPlayer;
};

#endif // RENDERTHREAD_H
